########################################################################
#  Searx-qt - Lightweight desktop application for SearX.
#  Copyright (C) 2020  CYBERDEViL
#
#  This file is part of Searx-qt.
#
#  Searx-qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################

from PyQt5.QtCore import pyqtSignal, QObject

from searxqt.core.searx import SearX


class SearchStatus:
    Done = 0
    Busy = 1


class SearchBehaviour:
    Normal = 0
    RandomEvery = 1


class SearchModel(QObject, SearX):
    statusChanged = pyqtSignal(int)  # SearchStatus
    optionsChanged = pyqtSignal()

    def __init__(self, requestsSettings, parent=None):
        QObject.__init__(self, parent=parent)
        SearX.__init__(self)
        self._requestsSettings = requestsSettings

        self._status = SearchStatus.Done
        self._randomEveryRequest = False
        self._useFallback = True

    @property
    def requestSettings(self): return self._requestsSettings

    # Options
    @property
    def useFallback(self):
        """
        @rtype: bool
        """
        return self._useFallback

    @useFallback.setter
    def useFallback(self, state):
        """
        @type state: bool
        """
        self._useFallback = state
        self.optionsChanged.emit()

    @property
    def randomEvery(self):
        """
        @rtype: bool
        """
        return self._randomEveryRequest

    @randomEvery.setter
    def randomEvery(self, state):
        """
        @type state: bool
        """
        self._randomEveryRequest = state
        self.optionsChanged.emit()

    # End options

    def status(self): return self._status

    def saveSettings(self):
        """ Returns current state
        """
        return {
            'fallback': self.useFallback,
            'randomEvery': self.randomEvery
        }

    def loadSettings(self, data):
        """ Restore current state

        @type data: dict
        """
        self.useFallback = data.get('fallback', True)
        self.randomEvery = data.get('randomEvery', False)

    """ SearX re-implementations below
    """
    def search(self, requestKwargs={}):
        self.statusChanged.emit(SearchStatus.Busy)
        result = SearX.search(self, requestKwargs)
        self.statusChanged.emit(SearchStatus.Done)
        return result
